package com.motu.monstercity.server.game.verticle;

import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.protocol.CmdEnum;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBIapResult;
import com.motu.monstercity.protocol.CsGameIap.CSGameIapFinishResponse;
import com.motu.monstercity.server.game.logic.GameIapManager;
import com.motu.monstercity.server.game.logic.GameUser;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;

public class IapVerticle extends AbstractVerticle {
    private final static Logger logger = MainVerticle.logger;

    @Override
    public void start(Promise<Void> future) throws Exception {

        EventBus eb = vertx.eventBus();

        String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_IAP);
        MessageConsumer<JsonObject> consumer = eb.consumer(ebName);

        consumer.handler(message -> {
            JsonObject data = message.body();
            long userId = data.getLong("user_id");
            JsonObject iapOrderObj = data.getJsonObject("obj");
            int count = 1;// 默认充值一笔
            if (iapOrderObj.containsKey("count")) {
                count = iapOrderObj.getInteger("count");
            }
            logger.info("--###########-- receive iap callback userId:" + userId + " obj:" + iapOrderObj.toString());
            try {
                String orderId = iapOrderObj.getString("order_id");
                CSGameIapFinishResponse.Builder res_build = CSGameIapFinishResponse.newBuilder();

                Common.PBUserData.Builder pbUserData = res_build.getUserBuilder();
                for (int i = 0; i < count; i++) {
                    if (count > 1) {// 多笔充值时需要生成订单号
                        iapOrderObj.put("order_id", orderId + i);
                    }
                    PBIapResult.Builder result = GameIapManager.dealOrder(pbUserData,userId, iapOrderObj, false);
                    //标记订单已处理
                    String sql = "update iap_order set error_code = 1 where user_id = ? and order_id = ?;";
                    JsonArray params = new JsonArray().add(userId).add(iapOrderObj.getString("order_id"));
                    MysqlTool.updateToDb(MysqlClient.getGamePool(), sql, params);
                    res_build.setIapResult(result);



                    JsonObject obj = ResponseUtils.getResponseData(CmdEnum.EnumCmdID.CMD_GAME_IAP_FINISH_VALUE, res_build.build().toByteArray());
                    GameUser.pushIapFinishToUser(userId, obj);

                    sendReply(message, new JsonObject());
                }
            } catch (Exception e) {
                logger.error(Tool.getException(e));
            }
        });

        consumer.completionHandler(res2 -> {
            if (res2.succeeded()) {
                logger.info("The IapVerticle handler registration has reached all nodes");
                future.complete();
            } else {
                logger.error("IapVerticle Registration failed! " + res2.cause().toString());
                future.fail(res2.cause());
            }
        });
    }

    private void sendReply(Message<JsonObject> message, JsonObject obj) {
        message.replyAndRequest(obj, h -> {
        });
    }

}
